package cn.linkai.star.graph.core.job;

import cn.hutool.core.date.DateTime;
import cn.linkai.star.graph.comfyui.client.api.ComfyuiApi;
import cn.linkai.star.graph.comfyui.client.pojo.ComfyuiTask;
import cn.linkai.star.graph.core.pojo.User;
import cn.linkai.star.graph.core.service.RedisService;
import cn.linkai.star.graph.core.service.UserFundRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.io.IOException;
import java.util.HashMap;

@RequiredArgsConstructor
@Component
@Slf4j
public class RunTaskJob {

    //注入
    private final ComfyuiApi comfyuiApi;
    private final RedisService redisService;
    private final RedissonClient redissonClient;
    private final UserFundRecordService userFundRecordService;

    private final static String SPRING_TASK_LOCK_KEY = "lock:task";
    public final static String TASK_RUN_SEMAPHORE = "TASK_RUN_SEMAPHORE";

    @Scheduled(cron = "0/1 * * * * ?")
    public void task(){
        //1、获取分布式锁
        RLock lock = redissonClient.getLock (SPRING_TASK_LOCK_KEY);
        //尝试获取锁，如果加锁成功，则继续执行任务
        if (lock.tryLock ()) {
            try {
//                log.info("开始执行任务");
                //尝试获取信号量
                if (redisService.hasQueueTask ()) {
                    RSemaphore semaphore = redissonClient.getSemaphore (TASK_RUN_SEMAPHORE);
                    if(semaphore.tryAcquire ()){
                        System.out.println (DateTime.now () + "\t\t获取许可证成功");
                        addTaskQueue ();
                    }
                }
            } finally {
                //执行完释放释放锁
                lock.unlock ();
            }
        }

    }

    private void addTaskQueue(){
        try {
            //1、从redis中获取序号最小的任务
            ComfyuiTask task = redisService.popQueueTask ();
            if(task == null){
                return;
            }

            //2、调用api将任务发送给Comfyui，并获取结果
            Response<HashMap> response = comfyuiApi.addQueueTask (task.getComfyuiRequestDto ()).execute ();
            if(response.isSuccessful ()){
                HashMap body = response.body ();
                String promptId = body.get ("prompt_id").toString ();
                //提交任务成功，将任务添加到redis中，用于后续查询结果
                task.setPromptId (promptId);
                log.info ("任务成功添加到队列,promptId:{}", promptId);
                redisService.addStartedTask (promptId, task);
            } else {
                String error = response.errorBody ().string ();
                log.error ("添加任务队列失败,error:{}", error);
                //冻结积分归还
                userFundRecordService.freezeReturn (task.getUserId (),task.getSize ());

                //释放信号量
                RSemaphore semaphore = redissonClient.getSemaphore (TASK_RUN_SEMAPHORE);
                semaphore.release ();
            }
        } catch (Exception e) {
            log.error("添加任务队列失败",e);
        }
    }
}
